﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Linq;
using ANGFLib;

namespace ANGF
{
    public partial class FormEditMain : Form
    {
        public FormEditMain()
        {
            InitializeComponent();
        }

        private static string fullpath = null;
        private static MyXmlDoc document = null;
        private void updateStatus()
        {
            this.label2.Text = fullpath ?? "---";
            if (document == null)
            {
                this.label4.Text = "---";
                this.label6.Text = "---";
                this.label8.Text = "---";
                this.label10.Text = "---";
                this.buttonSave.Enabled = false;
                this.buttonAddRegstry.Enabled = false;
            }
            else
            {
                this.label4.Text = document.id;
                this.label6.Text = document.name;
                var found = Scenarios.Modules.FirstOrDefault(c => c.id == document.shareWorld);
                this.label8.Text = found == null ? document.shareWorld : found.name + "(" + document.shareWorld + ")";
                if (document.versionInfo != null)
                {
                    this.label10.Text = document.versionInfo.ToString();
                }
                else
                {
                    this.label10.Text = "---";
                }
                this.buttonSave.Enabled = fullpath != null;
                this.buttonAddRegstry.Enabled = fullpath != null;
            }
            this.buttonChange.Enabled = document != null;
            this.buttonSaveAs.Enabled = document != null;
            this.buttonUpload.Enabled = document != null;
            this.buttonPlace.Enabled = document != null;
            this.buttonPerson.Enabled = document != null;
        }

        private bool isDirty = false;
        protected override void OnClosing(CancelEventArgs e)
        {
            if (isDirty)
            {
                var r = MessageBox.Show(this, "データを保存しますか?", this.Text, MessageBoxButtons.YesNoCancel);
                if (r == System.Windows.Forms.DialogResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }
                if (r == System.Windows.Forms.DialogResult.No) return;
                if (fullpath != null) buttonSave_Click(null, null);
                else
                {
                    bool r2 = saveAs();
                    if (r2) e.Cancel = true;
                }
            }
            base.OnClosing(e);
        }
        private void FormEditMain_Load(object sender, EventArgs e)
        {
            updateStatus();
        }

        private void kickFormEditModule(MyXmlDoc doc)
        {
            var form = new FormEditModule(doc);
            DialogResult result = form.ShowDialog(this);
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                if (doc == null) fullpath = null;
                document = form.GetResult();
                updateStatus();
                isDirty = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            kickFormEditModule(null);
        }

        private void buttonChange_Click(object sender, EventArgs e)
        {
            kickFormEditModule(document);
        }

        private void buttonSaveAs_Click(object sender, EventArgs e)
        {
            saveAs();
        }

        private bool saveAs()
        {
            if (document == null) return false;
            Stream myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    var doc = document.SaveToXDocument();
                    doc.Save(myStream);
                    myStream.Close();
                    fullpath = saveFileDialog1.FileName;
                    updateStatus();
                    isDirty = false;
                }
                else return true;
            }
            else return true;
            return false;
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (fullpath == null) return;
            if (document == null) return;
            var doc = document.SaveToXDocument();
            using (var myStream = new FileStream(fullpath, FileMode.Create))
            {
                doc.Save(myStream);
            }
            isDirty = false;
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            var mydoc = new MyXmlDoc();
                            mydoc.LoadFromXDocument(XDocument.Load(myStream), openFileDialog1.FileName);
                            fullpath = openFileDialog1.FileName;
                            document = mydoc;
                            updateStatus();
                            isDirty = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void buttonAddRegstry_Click(object sender, EventArgs e)
        {
            if (fullpath == null) return;
            if (document == null) return;
            Util.AddRegistry(this,document,fullpath);
        }

        private void buttonPlace_Click(object sender, EventArgs e)
        {
            if (document == null) return;
            var form = new FormEditComponentList(document, FormEditComponentList.EditComponentType.Place, typeof(FormEditPlace));
            if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) isDirty = true;
        }

        private void buttonPerson_Click(object sender, EventArgs e)
        {
            if (document == null) return;
            var form = new FormEditComponentList(document, FormEditComponentList.EditComponentType.Person, typeof(FormEditPerson));
            if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) isDirty = true;
        }

        private void buttonUpload_Click(object sender, EventArgs e)
        {
            if (fullpath == null) return;
            if (document == null) return;
            const string msg = @"これより公開専用サーバへのアップロードを行います。
無条件で公開されるので、テストが終わっていないモジュールのアップロードはお控え下さい。
また、システムファイルに記録されたキーが一致するシステムより差し替えのアップロードが可能となります。最初にアップロードしたときのシステムファイルを紛失しないようにご注意ください。このファイルはANGFのシステム機能のより保存できます。
本当にアップロードして公開を行いますか?";
            DialogResult r =  MessageBox.Show(this, msg, this.Text, MessageBoxButtons.YesNo);
            if (r != System.Windows.Forms.DialogResult.Yes) return;
            var doc = document.SaveToXDocument();
            Cursor.Current = Cursors.WaitCursor;
            string result = MyFileWS.FileWS.Upload(document.shareWorld, document.id, SystemFile.UserID, document.name, doc.ToString());
            Cursor.Current = Cursors.Default;
            if (result != null)
            {
                MessageBox.Show(this, result, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error );
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            var form = new FormEditWSFileSelect();
            var r = form.ShowDialog(this);
            if (r != System.Windows.Forms.DialogResult.OK) return;
            string target, module, name;
            form.GetResultNames( out target, out module, out name );

            var r2 = MessageBox.Show(this, name + "を公開サーバから削除しようとしています。本当に削除しますか?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            if (r2 != System.Windows.Forms.DialogResult.Yes) return;

            Cursor.Current = Cursors.WaitCursor;
            string r3 = MyFileWS.FileWS.Delete(target, module, SystemFile.UserID);
            Cursor.Current = Cursors.Default;
            if (r3 != null)
            {
                MessageBox.Show(this, r3, this.Text, MessageBoxButtons.OK,  MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show(this, name+"を公開サーバから削除しました。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
